import Common from '../common'
var Js = Common('subject')
export default {
  name: 'subject',
  components: {},
  mixins:[Js],
  data () {
    return {
      mainData: [],
      self:this,

      table_arguments:{
        height:'70%',
        row_key:'id',
        tree_props:{
          children: 'child',
          child: 'child',
          hasChildren:'child'
        },
        default_expand_all:false,
        expand:false,
        selection:true,
        cell_style:{},
        loading:true
      },
      fields: [
        {
        	key: '',
        	label: '答案',
        	application: [],
        	componentName: 'sls-input',
        	listType: 'normal',
        	width: 50
        },
        {
        	key: 'id',
        	label: 'ID',
        	application: [],
        	componentName: 'sls-input',
        	listType: 'normal',
        	width: 50
        },

        {
          key: 'paper_id',
          label: '试卷ID',
          application:['添加试卷题目'],
          componentName:'sls-input',
        },
        {
          key: 'score',
          label: '题目分数',
          application:['添加试卷题目'],
          componentName:'sls-input',
        },
        {
        	key: 'title',
        	label: '题目',
        	application: ['编辑', '添加'],
        	componentName: 'sls-textarea',
        	listType: 'normal',
        	customSlot: 'title',
        	header_search: {
        		componentName: 'sls-input',
        		placeholder: '请输入题目',
        		clearable: true,
        		changeFunc: function(val, self) {
        			if (val) {
        				self.searchItem.title = ['LIKE', ['%' + val + '%']];
        			} else {
        				delete self.searchItem.title;
        			}
        		}
        	}
        },
        {
        	key: 'passage1',
        	label: '答案解析',
        	application: ['编辑', '添加'],
        	componentName: 'sls-textarea',
        	listType: '',
        },
        {
        	key: 'listorder',
        	label: '排序',
        	application: ['设置', '添加'],
        	componentName: 'sls-input',
        	listType: 'normal',
        },
        {
        	key: 'score',
        	label: '分数',
        	application: ['设置', '添加'],
        	componentName: 'sls-input',
        	listType: 'normal',
        },
        {
        	key: "type",
        	label: '题目类型',
        	application: ['添加', '编辑'],
        	componentName: 'sls-select',
        	optionsName: 'typeOptions',
        	defaultProps: {
        		label: 'text',
        		value: 'value',
        		disabled: 'disabled',
        	},
        	formatter: function(val) {
        		if (val.type == 1) {
        			return '单选';
        		} else if (val.type == 2) {
        			return '多选';
        		} else if (val.type == 3) {
        			return '填空';
        		} else if (val.type == 4) {
        			return '判断';
        		} else if (val.type == 5) {
        			return '解答';
        		};
        	},
        	listType: '',
        },
        {
        	key: 'title',
        	label: '答案标签',
        	application: ['编辑答案', '添加答案'],
        	componentName: 'sls-input',
        	listType: '',
        	formatter: function(val) {

        	}
        },
        {
        	key: 'description',
        	label: '答案内容',
        	application: ['编辑答案', '添加答案'],
        	componentName: 'sls-textarea',
        	listType: '',
        },
        {
        	key: "is_right",
        	label: '状态',
        	application: ['编辑答案', '添加答案'],
        	componentName: 'sls-select',
        	optionsName: 'rightOptions',
        	defaultProps: {
        		label: 'text',
        		value: 'value',
        	}
        },
        {
        	key: 'create_time',
        	label: '创建时间',
        	listType: 'normal',
        	placeholder: '请选择创建时间',
        	header_search: {
        		componentName: 'sls-date-time-range',
        		style: 'width:160px;margin-right:2px;',
        		start_placeholder: '创建开始时间',
        		end_placeholder: '创建结束时间',
        		defaultValue: [],
        		changeFunc: function(value, self) {
        			if (!value) {
        				delete self.searchItem.create_time;
        			} else {
        				self.searchItem.create_time = ['between', value = value.map(function(e) {
        					return e / 1;
        				})];
        			};
        		},
        	},
        	width: 200
        },
        {
          label: '操作',
          listType:'deal',
          width:200
        },

      ],
      // 按钮配置
      btn_info: [
          {
            type:'info',
            icon:'edit',
            size:'mini',
            position:'header',
            text:function(data){
              return '添加'
            },
            func:{
              apiName:function(self){
                return "api_testPaperSubjectAdd"
              },
              formData:function(self){
                var data = {
                  title:'',
                  description:'',
                  mainImg:[],
                };
                return data
              },
              postData:function(self){
                var postData={
                  data:self.submitData
                };
                postData.paper_id = self.paperData.id;
                return postData;
              },
              callback:function(self){
                self.initPaperData()
              }
            },
          },

          {
            type:'info',
            icon:'edit',
            size:'mini',
            position:'list',
            text:function(data){
              return '编辑'
            },
            styleFunc: function(data) {
            	if (data.children) {
            		return 'display:block'
            	} else {
            		return 'display:none'

            	}
            },

            func:{
              apiName:function(self){
                return "api_subjectUpdate"
              },
              formData:function(self){
                return self.formData
              },
              postData:function(self){
                var postData={
                  searchItem:{
                    id:self.formData.id,
                    //user_no:self.formData.user_no
                  },
                  data:self.submitData
                };
                if(self.submitData.parentid&&self.submitData.parentid==self.formData.id){
                  self.$$notify('父级ID和子级ID重叠','fail');
                  return false;
                }else{
                  return postData;
                };

                if(postData.data.listorder||postData.data.score){
                  var newData = {};
                  if(postData.data.listorder){
                    self.paperData.subject_score_arr[self.formData.id]['listorder']  =postData.data.listorder;
                  };

                  if(postData.data.score){
                    self.paperData.subject_score_arr[self.formData.id]['score']  =postData.data.score;
                  };
                  postData.saveAfter = [{
                      tableName:'TestPaper',
                      FuncName:'update',
                      data:self.paperData.subject_score_arr,
                      searchItem:{id:self.paperData.id}
                  }];
                };

              }
            },
          },

          {
            type:'info',
            icon:'edit',
            size:'mini',
            position:'list',
            text:function(data){
              return '设置'
            },
            styleFunc: function(data) {
            	if (data.children) {
            		return 'display:block'
            	} else {
            		return 'display:none'

            	}
            },

            func:{
              apiName:function(self){
                return "api_testPaperUpdate"
              },
              formData:function(self){
                return self.formData
              },
              postData:function(self){

                if(self.submitData.listorder){
                  self.paperData.subject_score_arr[self.formData.id]['listorder']  =self.submitData.listorder;
                };

                if(self.submitData.score){
                  self.paperData.subject_score_arr[self.formData.id]['score']  =self.submitData.score;
                };


                var postData={
                  searchItem:{
                    id:self.paperData.id,
                    //user_no:self.formData.user_no
                  },
                  data:{
                    'subject_score_arr':self.paperData.subject_score_arr
                  }
                };
          //       if(self.submitData.parentid&&self.submitData.parentid==self.formData.id){
          //         self.$$notify('父级ID和子级ID重叠','fail');
          //         return false;
          //       }else{
          //         return postData;
          //       };

                console.log('postData',postData)
                return postData;

              }
            },
          },

          {
            type:'danger',
            icon:'delete',
            size:'mini',
            funcType:'submit',
            position:'header',
            text:function(data){
              return '删除选中'
            },
            func:{
              apiName:function(self){
                return "api_subjectUpdate"
              },
              postData:function(self){
                var deleteArray = [];
                for (var i = 0; i < self.selectionArray.length; i++) {
                  deleteArray.push(self.selectionArray[i].id);
                };
                var postData = {
                  searchItem:{
                    id:['in',deleteArray],
                  },
                  data:{
                    status:-1
                  }
                };
                return postData;
              }
            },
          },

         {
         	type: 'info',
         	icon: 'edit',
         	size: 'mini',
         	position: 'header',
         	text: function(data) {
         		return '返回'
         	},
         	funcType: 'func',
         	func: {
         		func: function(self) {
         			self.$router.push('/home/paper');
         		},
         	},
         },
         {
         	type: 'info',
         	icon: 'edit',
         	size: 'mini',
         	position: 'list',
         	text: function(data) {
         		return '添加答案'
         	},
         	styleFunc: function(data) {
         		if (data.children) {
         			return 'display:block'
         		} else {
         			return 'display:none'
         		}
         	},
         	func: {
         		apiName: function(self) {
         			return "api_subjectOptionsAdd"
         		},
         		formData: function(self) {
         			var data = {
         				is_right: 0
         			};
         			return data
         		},
         		postData: function(self) {
         			self.submitData.is_template = 1;
         			self.submitData.relation_id = self.originFormData.id;
         			var postData = {
         				data: self.submitData
         			};
         			return postData;
         		}
         	},
         },
         {
         	type: 'info',
         	icon: 'edit',
         	size: 'mini',
         	position: 'list',
         	text: function(data) {
         		return '编辑答案'
         	},
         	styleFunc: function(data) {
         		if (!data.children) {
         			return 'background-color: #c593e3;border-color:#c593e3'
         		} else {
         			return 'display:none'
         		}
         	},
         	func: {
         		apiName: function(self) {
         			return "api_subjectOptionsUpdate"
         		},
         		formData: function(self) {
         			return self.formData
         		},
         		postData: function(self) {
         			var postData = {
         				searchItem: {
         					id: self.formData.id
         				},
         				data: self.submitData
         			};
         			return postData;
         		}
         	},
         },
         {
         	type: 'danger',
         	icon: 'delete',
         	size: 'mini',
         	funcType: 'submit',
         	position: 'list',
         	text: function(data) {
         		return '删除答案'
         	},
         	styleFunc: function(data) {
         		if (!data.children) {
         			return 'background-color: #c593e3;border-color:#c593e3'
         		} else {
         			return 'display:none'
         		}
         	},
         	func: {
         		apiName: function(self) {
         			return "api_subjectOptionsUpdate"
         		},
         		postData: function(self) {
         			var postData = {
         				searchItem: {
         					id: self.originFormData.id
         				},
         				data: {
         					status: -1
         				}
         			};
         			return postData;
         		}
         	},
         },
          {
          	type: 'info',
          	icon: 'edit',
          	size: 'mini',
          	funcType: 'func',
          	position: 'header',
          	text: function(data) {
          		return '导入题目'
          	},
          	func: {
          		func: function(self) {
          			self.uploadClick()
          		},
          	},
          },
          {
          	type: 'info',
          	icon: 'edit',
          	size: 'mini',
          	funcType: 'func',
          	position: 'header',
          	text: function(data) {
          		return '重置试卷'
          	},
          	func: {
          		func: function(self) {
          			self.fixTestPaper()
          		},
          	},
          },
      ],
      paginate: {
        count: 0,
        currentPage: 1,
        pagesize:10,
        is_page:true,
        page_sizes: [10, 30, 60, 90],
        layout: 'total, sizes, prev, pager, next, jumper',
      },
      searchItem:{
        type:2
      },
      startSearchItem:{
        type:2
      },
      optionData:{
        labelOptions:[],
        statusOptions:[{
          text: '启用',
          value: 1
        }, {
          text: '禁用',
          value: -1
        }],
        typeOptions:[
          {text:'单选',value:1},
          {text:'多选',value:2},
          {text:'填空',value:3},
          {text:'判断',value:4},
          {text:'解答',value:5},
        ],
        rightOptions: [{
        	text: '正确',
        	value: 1
        }, {
        	text: '错误',
        	value: 0
        }],
      },
      otherData:{
      },
      UserInfo:{
        tableName:'UserInfo',
        searchItem:{
        },
        fixSearchItem:{
          status:1
        },
        key:'user_no',
        middleKey:'user_no',
        condition:'in',
      },
      dialog:{
        formLabelWidth:'auto',
        dialogFormVisible:false,
        title:'用户'
      },
      getBefore:{},
      formLabelWidth:'auto',
      btnName:'',
      formData:{},
      btnNow:{},
      submitData:{},
      orginFormData:{},
      selectionArray:[],
      paper_id:'',
      paperData:{}

    }

  },

  mounted () {
    this.init()
  },
  computed: {
    token: function () {
      return this.$store.getters.getToken
    }
  },
  watch: {
    $route (to, from) {
      // if(to.meta.clearFullPath=='/home/paperSubject'&&
      // to.params.id!=this.mainId){
      //   this.init()
      // };
    },
    token(){

    }
  },
  methods: {

    /**
     * 初始化
     */
    init () {
      this.paper_id = this.$route.params.id;
      this.parentid = this.$route.params.id;
      this.searchItem.parentid = this.parentid;
      this.startSearchItem.parentid = this.parentid;
      this.initPaperData()
    },

    async initPaperData (isNew) {

      const self = this;

      const postData  = {};
      postData.searchItem = {
        id:self.paper_id
      };
      var res =  await self.$$api_testPaperGet({data: postData});
      self.paperData = res.info.data[0];

      if(self.paperData['subject_comma'].length>0){
        self.searchItem = {
          id:['in',self.paperData['subject_comma']]
        };
        this.initMainData(true);
      }else{
        self.table_arguments.loading = false;
      };


    },

    async fixTestPaper () {

      const self = this;

      const postData  = {
        searchItem:{
          id:self.paper_id
        }
      };

      var res =  await self.$$api_fixTestPaper({data: postData});

      if(res.solely_code==100000){
        self.$message({
        	type: 'success',
        	message: '重置成功'
        });
      };


    },

    /**
     * 列表主函数
     */
    async initMainData (isNew) {

      const self = this;
      self.table_arguments.loading = true;
      const postData  = {};
      if(isNew){
        self.paginate.currentPage = 1;
      };
      postData.paginate = self.$$cloneForm(self.paginate);
      postData.token = self.$store.getters.getToken;
      if (self.searchItem) {
        postData.searchItem = self.$$cloneForm(self.searchItem)
      };
      if(JSON.stringify(self.getBefore) != "{}"){
        postData.getBefore = self.$$cloneForm(self.getBefore);
      };

      postData.orderField = {
        key:'id',
        value:self.paperData['subject_comma'].join(","),
      };
      postData.getAfter = {
      	children: {
      		tableName: 'SubjectOptions',
      		middleKey: 'id',
      		key: 'relation_id',
      		condition: '=',
      		order: {
      			id: 'asc'
      		}
      	}
      }
      var res =  await self.$$api_subjectGet({data: postData});
      self.mainData = res.info.data;

      for(var i=0;i<self.mainData.length;i++){
        self.mainData[i]['listorder'] = self.paperData.subject_score_arr[self.mainData[i]['id']]['listorder'];
        self.mainData[i]['score'] = self.paperData.subject_score_arr[self.mainData[i]['id']]['score'];
        for(var j=0;j<self.mainData[i]['children'].length;j++){
          self.mainData[i]['children'][j]['noSelect'] = true;
        };
      };
      self.paginate.count = res.info.total;
      self.table_arguments.loading = false;
    },

    uploadClick() {
    	const self = this;
    	self.$refs.uploadInput.click();
    },

    async upload(e) {
    	const self = this;
    	let file = e.target.files[0];
    	var obj = file.name.lastIndexOf(".");
    	var ext = file.name.substr(obj + 1);
    	let param = new FormData() // 创建form对象

    	param.append('excel', file, file.name) // 通过append向form对象添加数据
    	param.append('excelChangeKey', JSON.stringify({
    		'类型': 'type',
    		'标题': 'title',
    		'内容': 'description',
    		'分值': 'score',
    		'正确': 'is_right',
    		'答案解析': 'passage1',
    	}));
    	param.append('paper_id', self.id);


    	param.append('token', self.$store.getters.getToken);
    	param.append('ext', ext);
    	param.append('extension', ext);
    	param.append('md5', 'md5');
    	param.append('totalSize', file.size);
    	param.append('start', 0);
    	param.append('chunkSize', file.size);
    	param.append('originName', file.name);
    	// POST表单数据
    	//param.append('chunk', '0') // 添加form表单中其他数据
    	//console.log(param.get('file'))  FormData私有类对象，访问不到，可以通过get判断值是否传进去
    	let config = {
    		headers: {
    			'Content-Type': 'multipart/form-data'
    		}
    	}
    	//console.log(param.get('file'));
    	try {
    		var res = await self.$$api_importSubject({
    			data: param,
    			headers: {
    				'Content-Type': 'multipart/form-data'
    			}
    		});
    		if (res.solely_code == 100000) {
    			self.$$notify('导入成功', 'fail');
    			this.initMainData();
    		} else {
    			self.$$notify(res.msg, 'fail');
    		};
    		self.$refs.uploadInput.value = '';
    	} catch (e) {
    		self.$refs.uploadInput.value = '';
    	}

    },


  },


}
